package com.damie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.damie.common.jwtuilts.JwtUtil;
import com.damie.domain.User;
import com.damie.domain.UserAddress;
import com.damie.dto.UserAddressDto;
import com.damie.mapper.UserAddressMapper;
import com.damie.paramer.UserAddressParame;
import com.damie.paramer.UserAddressParameup;
import com.damie.service.UserAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Alon
 * @since 2021-01-19
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {

    @Resource
    private UserAddressMapper mapper;
    @Transactional
    @Override
    public UserAddressDto addAddress(UserAddressParame userAddressParame, HttpServletRequest request) throws Exception{
        String userId = getUserId(request);
        UserAddress userAddress = new UserAddress();
        BeanUtils.copyProperties(userAddressParame,userAddress);
        QueryWrapper<UserAddress> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        int insert = 0;
        int size = mapper.selectList(queryWrapper).size();
        if(size>0){
            //判断如果里面有地址了就是新增备用地址
            if (userAddressParame.getAddressStetus()==1){
                //用户前端新增时设置了默认地址,将新增的改为1其他的改成2
                System.out.println("用户主动设置默认地址");
                userAddress.setAddressStetus(2);
                userAddress.setUserId(userId.toString());
                insert = mapper.insert(userAddress);
                updateByUser(userAddress.getAddressId(), request);
                userAddress = mapper.selectById(userAddress.getAddressId());
            }else {
                System.out.println("备用地址");
                userAddress.setAddressStetus(2);
                userAddress.setUserId(userId.toString());
                insert = mapper.insert(userAddress);
            }
        }else {
            //判断如果里面没有地址了就是新增默认地址
            System.out.println("默认地址");
            userAddress.setAddressStetus(1);
            userAddress.setUserId(userId.toString());
            insert = mapper.insert(userAddress);
        }
        if (insert<=0){
            throw new RuntimeException("新增失败");
        }
        UserAddressDto userAddressDto = new UserAddressDto();
        BeanUtils.copyProperties(userAddress,userAddressDto);
        return userAddressDto;
    }

    @Override
    public List<UserAddressDto> queryByUser(HttpServletRequest request) {
        String userId = getUserId(request);
        QueryWrapper<UserAddress> objectQueryWrapper = new QueryWrapper<>();
        System.out.println(userId);
        objectQueryWrapper.eq("user_id",userId);
        List<UserAddress> userAddresses = mapper.selectList(objectQueryWrapper);
        List<UserAddressDto> collect = userAddresses.stream().map(userAddress -> {
            UserAddressDto userAddressDto = new UserAddressDto();
            BeanUtils.copyProperties(userAddress, userAddressDto);
            return userAddressDto;
        }).collect(Collectors.toList());
        System.out.println(collect);
        return collect;
    }

    @Override
    public UserAddressDto queryById(String addressId) {
        UserAddress userAddress = mapper.selectById(addressId);
        UserAddressDto userAddressDto = new UserAddressDto();
        BeanUtils.copyProperties(userAddress,userAddressDto);
        return userAddressDto;
    }
    @Transactional
    @Override
    public List<UserAddress> updateByUser(String addressId,HttpServletRequest request) {
        String userId = getUserId(request);
        QueryWrapper<UserAddress> wrapper = new QueryWrapper();
        wrapper.eq("user_id",userId);
        List<UserAddress> userAddresses = mapper.selectList(wrapper);
        List<UserAddress> collect = userAddresses.stream().map(userAddress -> {
            if (userAddress.getAddressId().equals(addressId)) {
                System.out.println("修改默认地址");
                userAddress.setAddressStetus(1);
            }else {
                System.out.println("修改备用地址");
                userAddress.setAddressStetus(2);
            }
            mapper.updateById(userAddress);
            return userAddress;
        }).collect(Collectors.toList());
        return collect;
    }
    @Transactional
    @Override
    public UserAddress deleteByUser(String addressId, HttpServletRequest request) {
        String userId = getUserId(request);
        //删除只能删除自己的地址
        QueryWrapper<UserAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("address_id",addressId);
        UserAddress userAddress = mapper.selectOne(wrapper);
        int i = -1;
        if(ObjectUtils.isNotEmpty(userAddress)){
            if (userAddress.getAddressStetus()==1){
                userAddress.setAddressStetus(2);
                mapper.updateById(userAddress);
                mapper.deleteById(addressId);
                //默认地址被删除随机一个其他默认地址
                QueryWrapper<UserAddress> wrappers = new QueryWrapper<>();
                wrappers.eq("user_id",userId);
                List<UserAddress> userAddresses = mapper.selectList(wrappers);
                updateByUser(userAddresses.get(0).getAddressId(), request);
                i=1;
            }else {
                i = mapper.deleteById(addressId);
            }
            if (i>0){
                return userAddress;
            }
            throw new RuntimeException("删除失败,服务器异常");
        }
        throw new RuntimeException("删除失败,未找到删除地址");
    }

    public String getUserId(HttpServletRequest request){
        String token = request.getHeader("token");
        Claims claims = JwtUtil.parseToken(token);
        Object userId = claims.get("userId");
        return userId.toString();
    }

    @Override
    public UserAddressDto updateAddress(UserAddressParameup userAddressParameup, HttpServletRequest request) throws Exception {
        if (userAddressParameup.getAddressId()==null){
            UserAddressParame userAddressParame = new UserAddressParame();
            userAddressParame.setAddressLatitude(29.577078);
            userAddressParame.setAddressLongitude(106.530949);
            userAddressParame.setAddressStetus(2);
            userAddressParame.setAddressName(userAddressParameup.getAddressName());
            userAddressParame.setUserPhone(userAddressParameup.getUserPhone());
            userAddressParame.setUserName(userAddressParameup.getUserName());

            UserAddressDto userAddressDto = addAddress(userAddressParame, request);
            return userAddressDto;
        }else {
            QueryWrapper<UserAddress> userAddressDtoQueryWrapper = new QueryWrapper<>();
            userAddressDtoQueryWrapper.eq("address_id", userAddressParameup.getAddressId());
            UserAddress userAddress = mapper.selectOne(userAddressDtoQueryWrapper);
            if (ObjectUtils.isEmpty(userAddress)){
                throw new RuntimeException("修改对象不存在");
            }
            UserAddress userAddressParame = new UserAddress();
            BeanUtils.copyProperties(userAddressParameup,userAddressParame);
            mapper.updateById(userAddressParame);
            UserAddressDto userAddresss = new UserAddressDto();
            BeanUtils.copyProperties(userAddressParameup,userAddresss);
            return userAddresss;
        }
    }
}
